//
//  TKYSelectedFileController.m
//  StationHouseHelper
//
//  Created by apple on 2018/7/2.
//  Copyright © 2018年 铁科院. All rights reserved.
//

#import "TKYSelectedFileController.h"
#import "TKYChangeStationHouseController.h"
#import "UIViewController+CWLateralSlide.h"
#import "FileCell.h"

#define KFileCellID @"FileCell"
#define kCell_Height 44
@interface TKYSelectedFileController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,UISearchResultsUpdating>

@property (nonatomic, strong)NSString *fileNameStr;

@property (nonatomic, strong) BaseTabelView *tableV;

@property (nonatomic, strong) NSMutableDictionary *results;


@property (nonatomic, strong)NSDictionary  *dataSource;
@property (nonatomic, strong)NSMutableArray  *sectionArray;
@property (nonatomic, strong)NSMutableArray  *stateArray;
//@property (nonatomic, strong)NSMutableArray *selectedArray;
@property (nonatomic, assign) NSIndexPath *selIndex;   //单选选中的行
@property(nonatomic,strong) UISearchController *svc;// 搜索条



@end

@implementation TKYSelectedFileController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initDataSource];
    [self setUPUI];
    //[self.view addSubview:self.tableV];
}

/**
 设置界面
 */
- (void)setUPUI{
    self.navigationItem.title = @"文档选择";
    self.navigationController.navigationBar.barTintColor = KNavColor;
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor whiteColor],NSFontAttributeName:[UIFont systemFontOfSize:19.0]}];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(backBarButtonItem:)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(tureAction:)];
    
    [self.view addSubview:self.tableV];
    
    [self setBarButtonItem];
}

- (void)backBarButtonItem:(UIBarButtonItem *)barButtonItem{
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)tureAction:(UIBarButtonItem *)barButtonItem{
    self.returnValueBlock(self.fileNameStr);
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setBarButtonItem
{
    //隐藏导航栏上的返回按钮
    [self.navigationItem setHidesBackButton:YES];
    CGFloat searchBarHei;
    if (@available(iOS 11.0, *)) {
        searchBarHei = 55;
    }else {
        searchBarHei = 44;
    }
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.svc=[[UISearchController alloc]initWithSearchResultsController:nil];
    [self.svc.searchBar sizeToFit];   //大小调整
    _svc.hidesNavigationBarDuringPresentation = NO;
   
    _svc.dimsBackgroundDuringPresentation = YES;
    _svc.obscuresBackgroundDuringPresentation = NO;
    //_svc.searchBar.backgroundImage =  [UIImage imageWithColor:[UIColor whiteColor]];
    _svc.searchBar.barTintColor = [UIColor whiteColor];
    _svc.searchBar.tintColor = [UIColor redColor];
    //拿到searchBar的输入框
    UITextField *searchTextField = [self.svc.searchBar valueForKey:@"_searchField"];
    //字体大小
    searchTextField.font = [UIFont systemFontOfSize:15];
    //输入框背景颜色
    searchTextField.backgroundColor = kRGBColor(248, 248, 248, 1);

    //设置搜索控制器的结果更新代理对象
    self.svc.searchResultsUpdater=self;
    self.svc.searchBar.delegate=self;
    self.svc.searchBar.frame = CGRectMake(0, MyNavBarHeight, kScreenWidth,searchBarHei);
    self.tableV.tableHeaderView = self.svc.searchBar;
    //解决：退出时搜索框依然存在的问题
    self.definesPresentationContext = YES;
    //去掉背景颜色上下两条黑色的线
    UIImageView *barImageView = [[[self.svc.searchBar.subviews firstObject] subviews] firstObject];
    barImageView.layer.borderColor = kRGBColor(248,248,248,1).CGColor;
    barImageView.layer.borderWidth = 1;
    
    UILabel *line = [[UILabel alloc]initWithFrame:CGRectMake(0, self.svc.searchBar.kx_bottom-1, kScreenWidth, 1)];
    line.backgroundColor =  kRGBColor(229, 229, 229, 1);
    [self.view addSubview:line];
    
}

#pragma mark - UISearchResultsUpdating
/**实现更新代理*/
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    //获取到用户输入的数据
    NSString *searchText = searchController.searchBar.text;
    
    
    //清除搜索结果
    if (self.results != nil) {
        [self.results removeAllObjects];
    }
    
    // 先取出字典里所有的key放到数组
    NSArray *arr = [self.dataSource allKeys];
    
    for (int i = 0; i < arr.count; i++) {
        // 对应key取出value  是个数组
        NSArray *reArr = [self.dataSource objectForKey:arr[i]];
        // 需要创建一个新数组 保证每个value都会有个数组创建
        NSMutableArray *mm = [NSMutableArray array];
        for (NSString *person in reArr) {
            if ([person.lowercaseString rangeOfString:searchText.lowercaseString].location != NSNotFound) {
                [mm addObject:person];
            }
        }
        if (mm.count > 0) {
            [self.results setObject:mm forKey:arr[i]];
        }
    }
    
    NSLog(@"selectedGroupVc  %@",self.results);
    /**通知结果ViewController进行更新*/
    [self.tableV reloadData];
}

#pragma mark UISearchBarDelegate
// return NO to not become first responder
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    NSLog(@"%s",__func__);
    return YES;
}

// called when text starts editing
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    NSLog(@"%s",__func__);
    NSLog(@"searchBar.text = %@",searchBar.text);
    [self.tableV reloadData];
}

// return NO to not resign first responder
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {
    NSLog(@"%s",__func__);
    return YES;
}

// called when text ends editing
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
    NSLog(@"%s",__func__);
    NSLog(@"searchBar.text = %@",searchBar.text);
}

// called before text changes
- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    NSLog(@"%s",__func__);
    NSLog(@"searchBar.text = %@",searchBar.text);
    return YES;
}

// called when text changes (including clear)
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    NSLog(@"%s",__func__);
    NSLog(@"searchBar.text = %@",searchBar.text);
}

// called when keyboard search button pressed 键盘搜索按钮
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    NSLog(@"%s",__func__);
    NSLog(@"searchBar.text = %@",searchBar.text);
    if (!self.svc.active) {
        [self.tableV reloadData];
    }
    [self.svc.searchBar resignFirstResponder];
}

// called when bookmark button pressed
- (void)searchBarBookmarkButtonClicked:(UISearchBar *)searchBar{
    NSLog(@"%s",__func__);
}

// called when cancel button pressed
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    NSLog(@"%s",__func__);
    [self.tableV reloadData];
}

// called when search results button pressed
- (void)searchBarResultsListButtonClicked:(UISearchBar *)searchBar{
    NSLog(@"%s",__func__);
}


#pragma mark-- 初始化数据
- (void)initDataSource
{
    self.sectionArray  = [NSMutableArray arrayWithObjects:@"文件1",
                          @"文件2",
                          @"文件3",
                          @"文件4",nil];
    
    NSArray *one = @[@"文件1",@"文件1",@"文件1"];
    NSArray *two = @[@"文件2",@"文件2？",@"文件2"];
    NSArray *three = @[@"文件3",@"文件3",@"文件3"];
    NSArray *four = @[@"文件4文件4文件4文件4文件4文件4",@"文件4",@"文件4",@"文件4"];
    
    // self.dataSource = [NSMutableArray arrayWithObjects:one,two,three,four, nil];
    
    // 最好是 这种列表是个字典   key 是页眉  里面value是数组 数组里面是各个cell
    self.dataSource = @{@"文件1":one,@"文件2":two,@"文件3":three};
    self.stateArray = [NSMutableArray array];
    
    for (int i = 0; i < self.dataSource.count; i++)
    {
        //所有的分区都是闭合
        [self.stateArray addObject:@"0"];
    }
}

#pragma mark --- UITableViewDataSource,UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.svc.active )  {
        return self.results.count;
    }else {
        return self.dataSource.count;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([self.stateArray[section] isEqualToString:@"1"]){
        //如果是展开状态
        if (self.svc.active )  {
            NSArray *a = [self.results allKeys];
            return [[self.results objectForKey:a[section]] count];
        }else {
            NSArray *a = [self.dataSource allKeys];
            return [[self.dataSource objectForKey:a[section]] count];
            
        }
        
    }else{
        //如果是闭合，返回0
        return 0;
    }
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    FileCell *cell = [tableView dequeueReusableCellWithIdentifier:KFileCellID];
    cell.fileName.textAlignment = NSTextAlignmentLeft;
    
    
    if (self.svc.active)  {
        NSArray *a = [self.results allKeys];
        cell.fileName.text = [self.results objectForKey:a[indexPath.section]][indexPath.row];
    }else {
        NSArray *a = [self.dataSource allKeys];
        cell.fileName.text = [self.dataSource objectForKey:a[indexPath.section]][indexPath.row];
    }
    
    cell.backgroundColor = [UIColor whiteColor];
    cell.selectionStyle = UITableViewCellSelectionStyleDefault;
    cell.contentView.backgroundColor = [UIColor whiteColor];
    if (_selIndex == indexPath) {
        [cell.selectedButton setImage:[UIImage imageNamed:@"选中.png"] forState:UIControlStateNormal];
    }else{
        [cell.selectedButton setImage:[UIImage imageNamed:@"非选中.png"] forState:UIControlStateNormal];
    }
    __weak typeof(cell) weakCell = cell;
    cell.selectedButtonCellBlock = ^(UIButton *sender) {
        NSLog(@"%@",weakCell.fileName.text);
        self.fileNameStr = weakCell.fileName.text;
        //取消之前的选择
        FileCell *cell = [tableView cellForRowAtIndexPath:_selIndex];
        // celled.accessoryType = UITableViewCellAccessoryNone;
        [cell.selectedButton setImage:[UIImage imageNamed:@"非选中.png"] forState:UIControlStateNormal];
        
        //记录当前的选择的位置
        self.selIndex = indexPath;
        
        //当前选择的
        FileCell *cell2  = [tableView cellForRowAtIndexPath:indexPath];
        [cell2.selectedButton setImage:[UIImage imageNamed:@"选中.png"] forState:UIControlStateNormal];
        
        [self.tableV reloadData];
    };
    return cell;
}
//
//- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
//{
//    if (tableView == self.tableV) {
//        return self.sectionArray[section];
//    }else{
//        return @"";
//    }
//}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
    [button setTag:section+1];
    button.backgroundColor = [UIColor whiteColor];
    [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [button setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 60)];
    [button addTarget:self action:@selector(buttonPress:) forControlEvents:UIControlEventTouchUpInside];
    UILabel *line = [[UILabel alloc]initWithFrame:CGRectMake(0, button.frame.size.height-1, button.frame.size.width, 1)];
    line.backgroundColor = kMainColour;
    [button addSubview:line];
    
    UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(10, (kCell_Height-25)/2, 25, 25)];
    [imgView setImage:[UIImage imageNamed:@"folder"]];
    [button addSubview:imgView];
    
    UIImageView *_imgView = [[UIImageView alloc]initWithFrame:CGRectMake(self.view.frame.size.width-30, (kCell_Height-6)/2, 10, 6)];
    
    if ([self.stateArray[section] isEqualToString:@"0"]) {
        _imgView.image = [UIImage imageNamed:@"ico_listdown"];
    }else if ([self.stateArray[section] isEqualToString:@"1"]) {
        _imgView.image = [UIImage imageNamed:@"ico_listup"];
    }
    [button addSubview:_imgView];
    
    UILabel *tlabel = [[UILabel alloc]initWithFrame:CGRectMake(45, (kCell_Height-20)/2, 200, 20)];
    [tlabel setBackgroundColor:[UIColor clearColor]];
    [tlabel setFont:[UIFont systemFontOfSize:14]];
    // [tlabel setText:self.sectionArray[section]];
    
    if (self.svc.active) {
        NSArray *a = [self.results allKeys];
        [tlabel setText:a[section]];
    }else {
        NSArray *a = [self.dataSource allKeys];
        [tlabel setText:a[section]];
    }
    [button addSubview:tlabel];
    return button;
}

#pragma mark  -select cell

/**
 页眉按钮点击
 */
- (void)buttonPress:(UIButton *)sender//headButton点击
{
    //判断状态值
    if ([self.stateArray[sender.tag - 1] isEqualToString:@"1"]){
        //修改
        [self.stateArray replaceObjectAtIndex:sender.tag - 1 withObject:@"0"];
    }else{
        [self.stateArray replaceObjectAtIndex:sender.tag - 1 withObject:@"1"];
    }
    [self.tableV reloadSections:[NSIndexSet indexSetWithIndex:sender.tag-1] withRowAnimation:UITableViewRowAnimationAutomatic];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kCell_Height;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.00001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return kCell_Height;
}

#pragma mark -- 懒加载
- (BaseTabelView *)tableV{
    if (_tableV == nil) {
        _tableV = [[BaseTabelView alloc]initWithFrame:CGRectMake(0, MyNavBarHeight, kScreenWidth, kScreenHeight)style:UITableViewStyleGrouped];
        _tableV.delegate = self;
        _tableV.dataSource = self;
        [_tableV registerNib:[UINib nibWithNibName:@"FileCell" bundle:nil] forCellReuseIdentifier:KFileCellID];
    }
    return _tableV;
}


- (NSMutableDictionary *)results{
    if (_results == nil) {
        _results = [NSMutableDictionary dictionary];
    }
    return _results;
    
}

@end
